package utils

import (
	"fmt"
	"log"
	"net"
	"strconv"
	"strings"
)

// 获取指定网卡的 IPv4 地址
func GetNodeIDFromInterface(interfaceName string) (int64, error) {
	iface, err := net.InterfaceByName(interfaceName)
	if err != nil {
		return -1, fmt.Errorf("failed to get interface %s: %v", interfaceName, err)
	}

	addrs, err := iface.Addrs()
	if err != nil {
		return -1, fmt.Errorf("failed to get addresses for interface %s: %v", interfaceName, err)
	}

	for _, addr := range addrs {
		if ipNet, ok := addr.(*net.IPNet); ok && !ipNet.IP.IsLoopback() {
			ip := ipNet.IP.To4()
			if ip != nil {
				parts := strings.Split(ip.String(), ".")
				nodeID, _ := strconv.ParseInt(parts[len(parts)-1], 10, 64)
				return nodeID, nil
			}
		}
	}

	return -1, fmt.Errorf("no valid IPv4 address found for interface: %s", interfaceName)
}

// 自动适配第一个有效网卡（优先 en0）
func GetNodeIDWithPreference(preferredInterface string) int64 {
	// 优先检查指定的 `preferredInterface`
	if preferredInterface != "" {
		nodeID, err := GetNodeIDFromInterface(preferredInterface)
		if err == nil {
			fmt.Printf("Using preferred interface %s for Node ID: %d\n", preferredInterface, nodeID)
			return nodeID
		}
		fmt.Printf("Preferred interface %s is not valid: %v\n", preferredInterface, err)
	}

	// 遍历所有网卡，选择第一个有效的非回环网卡
	interfaces, err := net.Interfaces()
	if err != nil {
		log.Fatalf("Failed to list network interfaces: %v", err)
	}

	for _, iface := range interfaces {
		// 忽略未启用和回环网卡
		if iface.Flags&net.FlagUp == 0 || iface.Flags&net.FlagLoopback != 0 {
			continue
		}

		nodeID, err := GetNodeIDFromInterface(iface.Name)
		if err == nil {
			fmt.Printf("Using interface %s for Node ID: %d\n", iface.Name, nodeID)
			return nodeID
		}
	}

	log.Fatalf("No valid IP address found on any interface")
	return -1
}

func RunDemo() {
	// 优先使用 `en0`
	nodeID := GetNodeIDWithPreference("en0")
	fmt.Printf("Generated Node ID: %d\n", nodeID)
}
